---
import ToolButton from "./ToolButton.astro";
---

<!-- 目录按钮开始 -->
<ToolButton id="toc-button" tooltipText="目录" classStyle="hidden max-lg:block">
  <svg
    xmlns="http://www.w3.org/2000/svg"
    fill="none"
    viewBox="0 0 24 24"
    stroke-width="1.5"
    stroke="currentColor"
    class="w-8 h-8"
  >
    <path
      stroke-linecap="round"
      stroke-linejoin="round"
      d="M3.75 5.25h16.5m-16.5 4.5h16.5m-16.5 4.5h16.5m-16.5 4.5h16.5"></path>
  </svg>
</ToolButton>

<script>
  // 点击目录按钮切换侧边盒子和目录的显示/隐藏
  document.addEventListener('DOMContentLoaded', () => {
    const tocButton = document.getElementById('toc-button');
    const catalogElement = document.getElementById('article-catalog');
    const rightBoxFixed = document.getElementById('right-box-fixed');
    
    // 强制更新目录指示器位置的函数
    function updateCatalogIndicator() {
      // 触发滚动事件以更新指示器位置
      const scrollEvent = new Event('scroll');
      window.dispatchEvent(scrollEvent);
      
      // 如果scrollManager存在，直接调用handleScroll函数
      if (window.scrollManager) {
        window.scrollManager.trigger('contentBoxCatalog');
      } else {
        // 备选方案：手动更新指示器位置
        setTimeout(() => {
          const indicator = document.querySelector('.md-editor-catalog-indicator');
          const activeLink = document.querySelector('.md-editor-catalog-active');
          if (indicator && activeLink) {
            indicator.style.top = `${activeLink.offsetTop + 5}px`;
            indicator.style.opacity = '1';
          }
        }, 50); // 小延迟确保DOM更新完成
      }
    }
    
    if (tocButton && catalogElement && rightBoxFixed) {
      tocButton.addEventListener('click', () => {
        // 在移动设备上切换显示状态
        if (window.innerWidth <= 1024) {
          // 同时切换侧边盒子和目录的显示状态
          if (rightBoxFixed.classList.contains('max-lg:hidden')) {
            // 显示侧边盒子和目录
            rightBoxFixed.classList.remove('max-lg:hidden');
            rightBoxFixed.classList.add('max-lg:block');
            catalogElement.classList.remove('max-lg:hidden');
            catalogElement.classList.add('max-lg:block');
            
            // 强制更新目录指示器位置，解决第一次打开时的偏移问题
            updateCatalogIndicator();
          } else {
            // 隐藏侧边盒子和目录
            rightBoxFixed.classList.remove('max-lg:block');
            rightBoxFixed.classList.add('max-lg:hidden');
            catalogElement.classList.remove('max-lg:block');
            catalogElement.classList.add('max-lg:hidden');
          }
        }
      });
    }
  });
</script>
